package com.ocom.company.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ocom.common.entity.access.EntityMjRegionInfo;
import com.ocom.common.entity.card.EntityXfMerchantInfo;
import com.ocom.common.entity.company.EntityRecentAdminAccount;
import com.ocom.common.entity.human.EntityDeptInfo;
import com.ocom.common.enums.DataSourceEnum;
import com.ocom.common.enums.MasterSlaveEnum;
import com.ocom.common.request.company.GetLoginCompanyListRequest;
import com.ocom.common.request.human.GetDeptByIdsRequest;
import com.ocom.common.request.human.GetMjRegionByIdsRequest;
import com.ocom.common.request.payconfig.GetMerchInfoByIdsRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.vo.company.GetLoginCompanyListVo;
import com.ocom.company.dao.IDaoRecentAdminAccount;
import com.ocom.company.feign.AccessClient;
import com.ocom.company.feign.HumanClient;
import com.ocom.company.feign.PayConfigClient;
import com.ocom.company.service.RecentAdminAccountService;
import com.ocom.mysql.aspect.DataSourceAspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

@Service
public class RecentAdminAccountServiceImpl extends ServiceImpl<IDaoRecentAdminAccount, EntityRecentAdminAccount> implements RecentAdminAccountService {

    @Autowired
    private HumanClient humanClient;

    @Autowired
    private AccessClient accessClient;

    @Autowired
    private PayConfigClient payConfigClient;

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public boolean saveOrUpdate(Long companyId, EntityRecentAdminAccount recentAdminAccount) {
        EntityRecentAdminAccount entityRecentAdminAccount = this.getOne(Wrappers.lambdaQuery(EntityRecentAdminAccount.class)
                .eq(EntityRecentAdminAccount::getComId,recentAdminAccount.getComId())
                .eq(EntityRecentAdminAccount::getUserId,recentAdminAccount.getUserId())
                .eq(EntityRecentAdminAccount::getAdminId,recentAdminAccount.getAdminId())
        );
        if(ObjectUtil.isEmpty(entityRecentAdminAccount)){
            recentAdminAccount.setLoginTime(new Date());
            return this.save(recentAdminAccount);
        }else{
            entityRecentAdminAccount.setLoginTime(new Date());
            return this.updateById(entityRecentAdminAccount);
        }
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.MASTER)
    public boolean deleteRecent(Long companyId,Long adminId) {
        return this.remove(Wrappers.lambdaQuery(EntityRecentAdminAccount.class)
                .eq(EntityRecentAdminAccount::getAdminId,adminId)
                .lt(EntityRecentAdminAccount::getLoginTime, DateUtil.offset(new Date(), DateField.YEAR,-1)));
    }


    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<GetLoginCompanyListVo> selectAdminLoginList(GetLoginCompanyListRequest request) {
        QueryWrapper<GetLoginCompanyListVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("A.admin_id",request.getAdminId())
                .eq("M.status",0)
                .eq("C.is_agent",0)
                .apply("M.id = A.user_id  and C.com_id = M.com_id and R.role_id = M.role")
                .orderByDesc("A.login_time")
                .last("limit 20");
        return this.baseMapper.selectAdminLoginList(queryWrapper);
    }

    @Override
    @DataSourceAspect(type= DataSourceEnum.MAIN_DB,isMaster = MasterSlaveEnum.SLAVE)
    public List<GetLoginCompanyListVo> selectUserLoginList(Long companyId, GetLoginCompanyListRequest request) {
        QueryWrapper<GetLoginCompanyListVo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("M.status",0)
                .eq("C.is_agent",0)
                .eq("M.com_id",request.getComId())
                .gt(request.getQueryMode().equals(2),"M.role",2)
                .eq(request.getRole() > 20,"M.role",request.getRole())
                .eq(request.getDeptId()>0,"M.dept_id",request.getDeptId())
                .eq(request.getRegionId() > 0,"M.region_id", request.getRegionId())
                .eq(request.getMerchId()>0,"M.bns_id",request.getMerchId())
                .orderByDesc("role","M.create_time");
        return this.baseMapper.selectUserLoginList(queryWrapper);
    }

    @Override
    public List<GetLoginCompanyListVo> getLoginCompanyList(GetLoginCompanyListRequest request) {
        List<GetLoginCompanyListVo> getLoginCompanyList = new ArrayList<>();
        if(ObjectUtil.isEmpty(request.getDeptId())){request.setDeptId(0L);}
        if(ObjectUtil.isEmpty(request.getRole())){request.setRole(0L);}
        if(ObjectUtil.isEmpty(request.getRegionId())){request.setRegionId(0L);}
        if(ObjectUtil.isEmpty(request.getMerchId())){request.setMerchId(0L);}
        Map<Long,EntityDeptInfo> deptInfoMap = new HashMap<>();
        Map<Long,EntityMjRegionInfo> regionInfoMap = new HashMap<>();
        Map<Integer,EntityXfMerchantInfo> xfMerchantInfoMap = new HashMap<>();

        if(Lists.newArrayList(0).contains(request.getQueryMode())){
            getLoginCompanyList = this.selectAdminLoginList(request);
        }else if(Lists.newArrayList(1,2).contains(request.getQueryMode())){
            getLoginCompanyList = this.selectUserLoginList(request.getComId(), request);
            //获取部门
            Set<Long> deptIds = new HashSet<>();
            Set<Long> regionIds = new HashSet<>();
            Set<Integer> merchIds = new HashSet<>();

            for (GetLoginCompanyListVo getLoginCompanyListVo:getLoginCompanyList){
                if(getLoginCompanyListVo.getDeptId() > 0){
                    deptIds.add(getLoginCompanyListVo.getDeptId());
                }

                if(getLoginCompanyListVo.getRegionId() > 0){
                    regionIds.add(getLoginCompanyListVo.getRegionId());
                }

                if(getLoginCompanyListVo.getMerchId() > 0){
                    merchIds.add(getLoginCompanyListVo.getMerchId());
                }

            }

            if(ObjectUtil.isNotEmpty(deptIds)){
                GetDeptByIdsRequest getDeptByIdsRequest = new GetDeptByIdsRequest();
                getDeptByIdsRequest.setComId(request.getComId());
                getDeptByIdsRequest.setIds(Lists.newArrayList(deptIds));
                Result<List<EntityDeptInfo>> resultDept = this.humanClient.getDeptByIds(getDeptByIdsRequest);
                if(ObjectUtil.isNotEmpty(resultDept.getData())){
                    for (EntityDeptInfo entityDeptInfo:resultDept.getData()){
                        deptInfoMap.put(entityDeptInfo.getDeptId(),entityDeptInfo);
                    }
                }
            }

            if(ObjectUtil.isNotEmpty(regionIds)){
                GetMjRegionByIdsRequest getMjRegionByIdsRequest = new GetMjRegionByIdsRequest();
                getMjRegionByIdsRequest.setComId(request.getComId());
                getMjRegionByIdsRequest.setIds(Lists.newArrayList(regionIds));
                Result<List<EntityMjRegionInfo>> resultMjRegion =  this.accessClient.getMjRegionByIds(getMjRegionByIdsRequest);
                if(ObjectUtil.isNotEmpty(resultMjRegion.getData())){
                    for (EntityMjRegionInfo entityMjRegionInfo:resultMjRegion.getData()){
                        regionInfoMap.put(entityMjRegionInfo.getDeptId(),entityMjRegionInfo);
                    }
                }
            }

            if(ObjectUtil.isNotEmpty(merchIds)){
                GetMerchInfoByIdsRequest getMjRegionByIdsRequest = new GetMerchInfoByIdsRequest();
                getMjRegionByIdsRequest.setComId(request.getComId());
                getMjRegionByIdsRequest.setIds(Lists.newArrayList(merchIds));
                Result<List<EntityXfMerchantInfo>> resultMjRegionInfo =  this.payConfigClient.GetMerchInfoByIds(getMjRegionByIdsRequest);
                if(ObjectUtil.isNotEmpty(resultMjRegionInfo.getData())){
                    for (EntityXfMerchantInfo entityXfMerchantInfo:resultMjRegionInfo.getData()){
                        xfMerchantInfoMap.put(entityXfMerchantInfo.getMerchId(),entityXfMerchantInfo);
                    }
                }
            }


        }



        for (GetLoginCompanyListVo getLoginCompanyListVo:getLoginCompanyList){
            if(ObjectUtil.isEmpty(getLoginCompanyListVo.getRoleName()) && getLoginCompanyListVo.getRole() < 10000){
                getLoginCompanyListVo.setRoleName(getRoleName(getLoginCompanyListVo.getRole()));
            }
            getLoginCompanyListVo.setDeptName("");

            //部门
            if(getLoginCompanyListVo.getDeptId() > 0){
                if(ObjectUtil.isNotEmpty(deptInfoMap.get(getLoginCompanyListVo.getDeptId()))){
                    getLoginCompanyListVo.setDeptName(getLoginCompanyListVo.getDeptName()+deptInfoMap.get(getLoginCompanyListVo.getDeptId()).getDeptName());
                }else{
                    EntityDeptInfo entityDeptInfo = new EntityDeptInfo();
                    entityDeptInfo.setComId(getLoginCompanyListVo.getCompanyId());
                    entityDeptInfo.setDeptId(entityDeptInfo.getDeptId());
                    Result<EntityDeptInfo> resultA = this.humanClient.getDeptById(entityDeptInfo);
                    if(ObjectUtil.isNotEmpty(resultA.getData())){
                        getLoginCompanyListVo.setDeptName(getLoginCompanyListVo.getDeptName()+resultA.getData().getDeptName());
                        deptInfoMap.put(resultA.getData().getDeptId(),resultA.getData());
                    }
                }

            }

            //片区
            if(getLoginCompanyListVo.getRegionId() > 0){
                if(ObjectUtil.isNotEmpty(regionInfoMap.get(getLoginCompanyListVo.getRegionId()))){
                    getLoginCompanyListVo.setDeptName(getLoginCompanyListVo.getDeptName()+regionInfoMap.get(getLoginCompanyListVo.getRegionId()).getRegionName());
                }else{
                    EntityMjRegionInfo entityMjRegionInfo = new EntityMjRegionInfo();
                    entityMjRegionInfo.setRegionId(getLoginCompanyListVo.getRegionId());
                    entityMjRegionInfo.setComId(getLoginCompanyListVo.getCompanyId());
                    Result<EntityMjRegionInfo> resultB  = this.accessClient.getMjRegionInfo(entityMjRegionInfo);
                    if(ObjectUtil.isNotEmpty(resultB.getData())){
                        getLoginCompanyListVo.setDeptName(getLoginCompanyListVo.getDeptName()+resultB.getData().getRegionName());
                        regionInfoMap.put(resultB.getData().getRegionId(),resultB.getData());
                    }
                }

            }


            if(getLoginCompanyListVo.getMerchId() > 0){
                if(ObjectUtil.isNotEmpty(xfMerchantInfoMap.get(getLoginCompanyListVo.getMerchId()))){
                    getLoginCompanyListVo.setDeptName(getLoginCompanyListVo.getDeptName()+xfMerchantInfoMap.get(getLoginCompanyListVo.getMerchId()).getMerchName());
                }else{
                    Result<EntityXfMerchantInfo> resultC = payConfigClient.GetMerchInfo(getLoginCompanyListVo.getCompanyId(),getLoginCompanyListVo.getMerchId());
                    if(ObjectUtil.isNotEmpty(resultC.getData())){
                        getLoginCompanyListVo.setDeptName(getLoginCompanyListVo.getDeptName()+resultC.getData().getMerchName());
                        xfMerchantInfoMap.put(resultC.getData().getMerchId(),resultC.getData());
                    }
                }

            }

        }
        return getLoginCompanyList;
    }
    @Override
    public  String getRoleName(Long role){
        Map<Long,String> roleName = new HashMap<>();
        roleName.put(0L,"admin");
        roleName.put(1L,"OCOM销售");
        roleName.put(2L,"OCOM测试");
        roleName.put(11L,"代理商管理员");
        roleName.put(21L,"单位管理员");
        roleName.put(22L,"单位操作员");
        roleName.put(23L,"部门管理员");
        roleName.put(31L,"片区管理员");
        roleName.put(41L,"承包商");
        roleName.put(45L,"商户");
        roleName.put(51L,"大屏操作员");
        roleName.put(99L,"普通用户");
        roleName.put(100L,"临时访客");
        return roleName.get(role);
    }
}
